<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三班制排班管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <style>
        .shift-card {
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .shift-morning {
            border-left: 5px solid #4CAF50;
        }
        .shift-afternoon {
            border-left: 5px solid #2196F3;
        }
        .shift-night {
            border-left: 5px solid #673AB7;
        }
        .caregiver-badge {
            margin: 2px;
            font-size: 0.85rem;
        }
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        .status-success {
            background-color: #4CAF50;
        }
        .status-error {
            background-color: #F44336;
        }
        .schedule-date-nav {
            text-align: center;
            margin: 15px 0;
        }
        .tab-content {
            padding-top: 20px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <a class="navbar-brand" href="/">养老院排班系统</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="/">首页</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/schedule.html">排班管理</a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="/three_shift_schedule.html">三班制排班</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/elder.html">老人管理</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/caregiver.html">护理员管理</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">排班设置</h5>
                    </div>
                    <div class="card-body">
                        <form id="schedule-form">
                            <div class="form-group">
                                <label for="start-date">开始日期</label>
                                <input type="date" class="form-control" id="start-date" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="period-type">排班周期</label>
                                <select class="form-control" id="period-type" required>
                                    <option value="day">天</option>
                                    <option value="week">周</option>
                                    <option value="month">月</option>
                                    <option value="quarter">季度</option>
                                    <option value="year">年</option>
                                </select>
                            </div>
                            
                            <div class="form-group" id="period-length-group">
                                <label for="period-length">周期长度</label>
                                <input type="number" class="form-control" id="period-length" value="1" min="1" max="366" required>
                                <small class="form-text text-muted">天数(1-366)</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="shift-start-time">排班开始时间</label>
                                <input type="time" class="form-control" id="shift-start-time" value="08:00" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="day-night-weight">白天/黑夜权重比</label>
                                <input type="number" class="form-control" id="day-night-weight" value="0.618" min="0.1" max="10" step="0.001" required>
                                <small class="form-text text-muted">默认值: 0.618</small>
                            </div>
                            
                            <button type="submit" class="btn btn-primary btn-block mt-4" id="generate-btn">生成排班</button>
                        </form>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0">老人管理</h5>
                    </div>
                    <div class="card-body">
                        <button class="btn btn-outline-primary btn-block mb-2" id="add-elder-btn">添加老人需求</button>
                        <button class="btn btn-outline-secondary btn-block mb-2" id="update-arrangement-btn">更新参与状态</button>
                        <button class="btn btn-outline-info btn-block" id="select-elders-btn">选择老人参与排班</button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-9">
                <ul class="nav nav-tabs" id="scheduleTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="schedule-tab" data-toggle="tab" href="#schedule-content" role="tab">排班结果</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="elder-tab" data-toggle="tab" href="#elder-content" role="tab">老人列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="caregiver-tab" data-toggle="tab" href="#caregiver-content" role="tab">护理员列表</a>
                    </li>
                </ul>
                
                <div class="tab-content" id="scheduleTabsContent">
                    <div class="tab-pane fade show active" id="schedule-content" role="tabpanel">
                        <div class="alert alert-info" id="schedule-info">
                            请设置排班参数并点击"生成排班"按钮开始排班。
                        </div>
                        
                        <div id="schedule-loading" class="text-center d-none">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">加载中...</span>
                            </div>
                            <p class="mt-2">正在生成排班，请稍候...</p>
                        </div>
                        
                        <div id="schedule-results" class="d-none">
                            <div class="schedule-date-nav">
                                <button class="btn btn-sm btn-outline-secondary" id="prev-date">&lt; 前一天</button>
                                <span class="mx-3" id="current-date-display">2023-01-01</span>
                                <button class="btn btn-sm btn-outline-secondary" id="next-date">后一天 &gt;</button>
                            </div>
                            
                            <div class="row" id="shifts-container">
                                <!-- 班次卡片将通过JavaScript动态添加 -->
                            </div>
                        </div>
                    </div>
                    
                    <div class="tab-pane fade" id="elder-content" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped" id="elder-table">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="select-all-elders"></th>
                                        <th>ID</th>
                                        <th>老人</th>
                                        <th>需求活动</th>
                                        <th>参与排班</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 老人列表将通过JavaScript动态添加 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div class="tab-pane fade" id="caregiver-content" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped" id="caregiver-table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>护理员</th>
                                        <th>技能</th>
                                        <th>排班数量</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 护理员列表将通过JavaScript动态添加 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加/更新老人需求模态框 -->
    <div class="modal fade" id="elderDemandModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加/更新老人需求</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="elder-demand-form">
                        <div class="form-group">
                            <label for="elder-id">老人ID</label>
                            <input type="text" class="form-control" id="elder-id" required>
                        </div>
                        <div class="form-group">
                            <label for="elder-actions">需求活动</label>
                            <input type="text" class="form-control" id="elder-actions" placeholder="逗号分隔的活动ID" required>
                        </div>
                        <div class="form-group">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="elder-arrange" checked>
                                <label class="custom-control-label" for="elder-arrange">参与排班</label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-elder-demand">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 更新老人参与状态模态框 -->
    <div class="modal fade" id="updateArrangementModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更新老人参与状态</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>选择状态</label>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="participate-true" name="participate" class="custom-control-input" value="1" checked>
                            <label class="custom-control-label" for="participate-true">参与排班</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="participate-false" name="participate" class="custom-control-input" value="0">
                            <label class="custom-control-label" for="participate-false">不参与排班</label>
                        </div>
                    </div>
                    <div class="alert alert-warning">
                        将为所有选中的老人更新参与状态，请确认。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-arrangement">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 选择老人参与排班模态框 -->
    <div class="modal fade" id="selectEldersModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">选择老人参与排班</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>选择操作</label>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="include-true" name="include" class="custom-control-input" value="true" checked>
                            <label class="custom-control-label" for="include-true">包含在排班中</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="include-false" name="include" class="custom-control-input" value="false">
                            <label class="custom-control-label" for="include-false">从排班中排除</label>
                        </div>
                    </div>
                    <div class="alert alert-info">
                        此操作会记录选中的老人，在下次排班时自动处理。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-elder-selection">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/moment/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // 设置今天日期为默认值
            $('#start-date').val(new Date().toISOString().split('T')[0]);
            
            // 加载老人列表
            loadElders();
            
            // 加载护理员列表
            loadCaregivers();
            
            // 排班周期类型变化时更新周期长度提示
            $('#period-type').change(function() {
                const periodType = $(this).val();
                let maxValue = 366;
                let helpText = '天数(1-366)';
                
                switch(periodType) {
                    case 'week':
                        maxValue = 52;
                        helpText = '周数(1-52)';
                        break;
                    case 'month':
                        maxValue = 12;
                        helpText = '月数(1-12)';
                        break;
                    case 'quarter':
                        maxValue = 4;
                        helpText = '季度数(1-4)';
                        break;
                    case 'year':
                        maxValue = 1;
                        helpText = '年数(1)';
                        break;
                }
                
                $('#period-length').attr('max', maxValue);
                $('#period-length-group small').text(helpText);
                
                // 如果当前值大于最大值，更新为最大值
                if (parseInt($('#period-length').val()) > maxValue) {
                    $('#period-length').val(maxValue);
                }
            });
            
            // 生成排班表单提交
            $('#schedule-form').submit(function(e) {
                e.preventDefault();
                generateSchedule();
            });
            
            // 添加老人需求按钮点击
            $('#add-elder-btn').click(function() {
                $('#elder-id').val('');
                $('#elder-actions').val('');
                $('#elder-arrange').prop('checked', true);
                $('#elderDemandModal').modal('show');
            });
            
            // 保存老人需求按钮点击
            $('#save-elder-demand').click(function() {
                saveElderDemand();
            });
            
            // 更新参与状态按钮点击
            $('#update-arrangement-btn').click(function() {
                const selectedElders = getSelectedElders();
                if (selectedElders.length === 0) {
                    alert('请先选择老人');
                    return;
                }
                $('#updateArrangementModal').modal('show');
            });
            
            // 保存参与状态按钮点击
            $('#save-arrangement').click(function() {
                updateElderArrangement();
            });
            
            // 选择老人参与排班按钮点击
            $('#select-elders-btn').click(function() {
                const selectedElders = getSelectedElders();
                if (selectedElders.length === 0) {
                    alert('请先选择老人');
                    return;
                }
                $('#selectEldersModal').modal('show');
            });
            
            // 保存老人选择按钮点击
            $('#save-elder-selection').click(function() {
                selectEldersForScheduling();
            });
            
            // 全选/取消全选老人
            $('#select-all-elders').change(function() {
                const isChecked = $(this).prop('checked');
                $('#elder-table tbody input[type="checkbox"]').prop('checked', isChecked);
            });
            
            // 前一天按钮点击
            $('#prev-date').click(function() {
                navigateScheduleDate(-1);
            });
            
            // 后一天按钮点击
            $('#next-date').click(function() {
                navigateScheduleDate(1);
            });
        });
        
        // 加载老人列表
        function loadElders() {
            $.get('/elders', function(data) {
                $('#elder-table tbody').empty();
                
                $.each(data, function(i, elder) {
                    const row = `
                        <tr>
                            <td><input type="checkbox" class="elder-checkbox" data-id="${elder.elder}"></td>
                            <td>${elder.id}</td>
                            <td>${elder.elder}</td>
                            <td>${elder.actions}</td>
                            <td>${elder.arrange === '1' ? '是' : '否'}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary edit-elder" data-id="${elder.elder}" data-actions="${elder.actions}" data-arrange="${elder.arrange}">编辑</button>
                            </td>
                        </tr>
                    `;
                    $('#elder-table tbody').append(row);
                });
                
                // 绑定编辑按钮点击事件
                $('.edit-elder').click(function() {
                    const elderId = $(this).data('id');
                    const actions = $(this).data('actions');
                    const arrange = $(this).data('arrange');
                    
                    $('#elder-id').val(elderId);
                    $('#elder-actions').val(actions);
                    $('#elder-arrange').prop('checked', arrange === '1');
                    
                    $('#elderDemandModal').modal('show');
                });
            });
        }
        
        // 加载护理员列表
        function loadCaregivers() {
            $.get('/caregivers', function(data) {
                $('#caregiver-table tbody').empty();
                
                $.each(data, function(i, caregiver) {
                    const row = `
                        <tr>
                            <td>${caregiver.id}</td>
                            <td>${caregiver.attendant_name}</td>
                            <td>${caregiver.skills}</td>
                            <td>-</td>
                        </tr>
                    `;
                    $('#caregiver-table tbody').append(row);
                });
            });
        }
        
        // 生成排班
        function generateSchedule() {
            // 显示加载提示
            $('#schedule-info').addClass('d-none');
            $('#schedule-loading').removeClass('d-none');
            $('#schedule-results').addClass('d-none');
            
            // 获取表单数据
            const data = {
                start_date: $('#start-date').val(),
                period_type: $('#period-type').val(),
                period_length: parseInt($('#period-length').val()),
                shift_start_time: $('#shift-start-time').val(),
                day_night_weight: parseFloat($('#day-night-weight').val())
            };
            
            // 发送请求
            $.ajax({
                url: '/generate_and_process_schedule',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    // 隐藏加载提示
                    $('#schedule-loading').addClass('d-none');
                    $('#schedule-results').removeClass('d-none');
                    
                    // 设置当前显示日期
                    const startDate = new Date(data.start_date);
                    $('#current-date-display').text(startDate.toISOString().split('T')[0]);
                    $('#current-date-display').data('date', startDate.toISOString().split('T')[0]);
                    
                    // 加载排班结果
                    loadScheduleResult(startDate.toISOString().split('T')[0]);
                },
                error: function(xhr) {
                    // 显示错误信息
                    $('#schedule-loading').addClass('d-none');
                    $('#schedule-info').removeClass('d-none').removeClass('alert-info').addClass('alert-danger')
                        .text('排班生成失败: ' + (xhr.responseJSON ? xhr.responseJSON.error : '未知错误'));
                }
            });
        }
        
        // 加载指定日期的排班结果
        function loadScheduleResult(date) {
            $.get('/query_shift_schedule?date=' + date, function(data) {
                $('#shifts-container').empty();
                
                // 创建三个班次卡片
                const shiftClasses = {
                    '早班': 'shift-morning',
                    '中班': 'shift-afternoon',
                    '晚班': 'shift-night'
                };
                
                for (const [shiftName, slots] of Object.entries(data.shifts)) {
                    // 统计护理员
                    const caregivers = new Set();
                    const elders = new Set();
                    slots.forEach(slot => {
                        if (slot.caregiver !== '-') {
                            caregivers.add(slot.caregiver);
                        }
                        elders.add(slot.elder);
                    });
                    
                    // 创建卡片
                    const cardHtml = `
                        <div class="col-md-4">
                            <div class="card shift-card ${shiftClasses[shiftName]}">
                                <div class="card-header">
                                    <h5 class="mb-0">${shiftName}</h5>
                                </div>
                                <div class="card-body">
                                    <p><strong>时间段数:</strong> ${slots.length}</p>
                                    <p><strong>老人数:</strong> ${elders.size}</p>
                                    <p><strong>护理员数:</strong> ${caregivers.size}</p>
                                    <h6>护理员:</h6>
                                    <div class="caregiver-container">
                                        ${Array.from(caregivers).map(c => `<span class="badge badge-info caregiver-badge">${c}</span>`).join('')}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#shifts-container').append(cardHtml);
                }
            }).fail(function() {
                $('#shifts-container').html('<div class="col-12"><div class="alert alert-warning">未找到该日期的排班数据</div></div>');
            });
        }
        
        // 导航到前一天或后一天
        function navigateScheduleDate(delta) {
            const currentDate = new Date($('#current-date-display').data('date'));
            currentDate.setDate(currentDate.getDate() + delta);
            
            const newDate = currentDate.toISOString().split('T')[0];
            $('#current-date-display').text(newDate);
            $('#current-date-display').data('date', newDate);
            
            loadScheduleResult(newDate);
        }
        
        // 保存老人需求
        function saveElderDemand() {
            const data = {
                elder: $('#elder-id').val(),
                actions: $('#elder-actions').val(),
                arrange: $('#elder-arrange').prop('checked') ? '1' : '0'
            };
            
            $.ajax({
                url: '/add_elder_demand',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    $('#elderDemandModal').modal('hide');
                    loadElders();
                },
                error: function(xhr) {
                    alert('保存失败: ' + (xhr.responseJSON ? xhr.responseJSON.error : '未知错误'));
                }
            });
        }
        
        // 获取选中的老人ID
        function getSelectedElders() {
            const selectedElders = [];
            $('#elder-table tbody input[type="checkbox"]:checked').each(function() {
                selectedElders.push($(this).data('id'));
            });
            return selectedElders;
        }
        
        // 更新老人参与状态
        function updateElderArrangement() {
            const data = {
                elders: getSelectedElders(),
                arrange: $('input[name="participate"]:checked').val()
            };
            
            $.ajax({
                url: '/update_elder_arrangement',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    $('#updateArrangementModal').modal('hide');
                    loadElders();
                },
                error: function(xhr) {
                    alert('更新失败: ' + (xhr.responseJSON ? xhr.responseJSON.error : '未知错误'));
                }
            });
        }
        
        // 选择老人参与排班
        function selectEldersForScheduling() {
            const data = {
                elders: getSelectedElders(),
                include: $('input[name="include"]:checked').val() === 'true'
            };
            
            $.ajax({
                url: '/select_elders_for_scheduling',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    $('#selectEldersModal').modal('hide');
                    alert(response.message);
                },
                error: function(xhr) {
                    alert('操作失败: ' + (xhr.responseJSON ? xhr.responseJSON.error : '未知错误'));
                }
            });
        }
    </script>
</body>
</html> 